package com.originskyseed.platform.count.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.service.IDeptService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.count.i18n.CountResponseMsg;
import com.originskyseed.platform.count.model.UserSalary;
import com.originskyseed.platform.count.service.IUserSalaryService;
import com.originskyseed.platform.count.vo.request.UserSalaryRequestVO;

/**
 * 用户工资信息表Controller类（OSI_USER_SALARY）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/userSalary")
@BaseLocaleResource(localeFileName = "i18n_count")
public class UserSalaryController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserSalaryController.class);

	@DubboReference
	private IUserSalaryService userSalaryService;

	@DubboReference
	private IDeptService deptService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userSalaryList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<UserSalary>> userSalaryList(HttpServletRequest request) {
		BaseResponseBody<BasePage<UserSalary>> result = null;
		try {
			// 请求对象
			UserSalaryRequestVO requestVO = this.getParameterBean(UserSalaryRequestVO.class);

			// 分页查询
			BasePage<UserSalary> page = new BasePage<UserSalary>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.userSalaryService.selectListByPage(requestVO.toMap(), page);
			for (UserSalary userSalary:page.getResults()) {
				Dept dept = this.deptService.selectByPrimaryKey(userSalary.getDeptId());
				if (dept!=null){
					userSalary.setDept(dept.getName());
					userSalary.setCostDept(dept.getName());
					userSalary.setSubject(getSubjectDept(dept.getCode()));
				}

				String type = "";
				if(userSalary.getType().equals("0")){
					type = "总裁";
				}else if(userSalary.getType().equals("1")){
					type = "体系";
				}else if(userSalary.getType().equals("2")){
					type = "分公司/频道";
				}else if(userSalary.getType().equals("3")){
					type = "部门";
				}else if(userSalary.getType().equals("4")){
					type = "事业厅";
				}else if(userSalary.getType().equals("5")){
					type = "小组";
				}else if(userSalary.getType().equals("6")){
					type = "业务员";
				}else if(userSalary.getType().equals("7")){
					type = "内容总裁";
				}else if(userSalary.getType().equals("8")){
					type = "内容体系";
				}else if(userSalary.getType().equals("9")){
					type = "内容频道";
				}else if(userSalary.getType().equals("10")){
					type = "内容运营小组";
				}else if(userSalary.getType().equals("11")){
					type = "内容主播";
				}
				userSalary.setType(type);

				// 脱密
				String phone = userSalary.getPhone();
				String idCardNum = userSalary.getIdCardNum();
				if (phone != null && StringUtils.isNotBlank(phone)) {
					if(phone.length()>=11) {
						userSalary.setPhone(phone.substring(0, 3) + "****" + phone.substring(7, 11));
					}
				}
				if (idCardNum != null && StringUtils.isNotBlank(idCardNum)) {
					if(idCardNum.length()>=14) {
						userSalary.setIdCardNum(idCardNum.substring(0, 14) + "****");
					}
				}
			}
			result = new BaseResponseBody<BasePage<UserSalary>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<UserSalary>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userSalarySave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<UserSalary> userSalarySave(HttpServletRequest request) {
		BaseResponseBody<UserSalary> result = null;
		try {
			// 请求对象
			UserSalary userSalary = this.getParameterBean(UserSalary.class);

			if (StringUtils.isNotBlank(userSalary.getId())) {
				this.userSalaryService.updateByPrimaryKey(userSalary);
			} else {
				this.userSalaryService.insertSelective(userSalary);
			}
			result = new BaseResponseBody<UserSalary>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SAVE_SUCCESS.getMsg()), userSalary);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<UserSalary>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userSalaryDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> userSalaryDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.userSalaryService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 导出工资结算Excel
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/userSalaryExport.json")
	public BaseResponseBody userSalaryExport(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			UserSalaryRequestVO requestVO = this.getParameterBean(UserSalaryRequestVO.class);
			List<UserSalary> list = this.userSalaryService.selectListByMap(requestVO.toMap());
			// excel标题
			String[] title = { "序号", "日期", "员工账号", "姓名", "员工状态", "核发主体","所属主体","部门", "成本部门", "军衔等级", "岗位", "入职日期","离职日期","手机号码"
					, "身份证号码", "银行卡", "开户行","工资总额","基本工资", "应出勤天数", "实际出勤天数", "基本工资总额", "绩效工资","实发绩效总额","奖金"
					, "全勤/小蜜蜂奖", "奖金总额", "餐费（扣款/补贴）", "等级/加班补贴","内荐费","房补", "社保补贴", "上月25号以后入职工资（含25号）", "其他补贴", "补贴总额","扣迟到早退","病假天数"
					, "扣病假", "事假（H)", "扣事假", "扣漏打卡","宿舍扣款","违规处罚扣款", "其他扣款", "实际扣款总额", "当月应发工资", "截止上月累计应发工资","应发工资合计","当月养老扣除"
					, "当月医疗扣除", "当月失业扣除", "当月公积金扣除", "当月个人五险一金扣款","截止上月累计个人五险一金扣款","个人五险一金扣款合计", "当月应发工资（已扣社保费）", "截止上月累计税前减免", "累计税前减免", "累计基本费用扣除","累计子女教育专项扣除","累计继续教育专项扣除"
					, "累计住房贷款专项扣除", "累计住房租金专项扣除", "累计赡养老人专项扣除", "累计大病医疗专项扣除","专项附加扣除合计","累计预扣预缴应纳税所得额", "本期应预扣预缴税额", "已预扣预缴税额", "本期实际应预扣预缴税额", "税后扣其它","实发工资"
			};
			String fileName = "业务员工资结算";
			String sheetName = "业务员工资结算";

			String[][] values = new String[list.size()][];
			for (int i = 0; i < list.size(); i++) {
				values[i] = new String[title.length];
				// 将对象内容转换成string
				UserSalary obj = list.get(i);
				// 获取部门
				Dept dept = this.deptService.selectByPrimaryKey(obj.getDeptId());
				if (dept!=null){
					obj.setDept(dept.getName());
					obj.setCostDept(dept.getName());
					obj.setSubject(getSubjectDept(dept.getCode()));
				}
				values[i][0] = i+1 + "";
				values[i][1] = obj.getMonth();
				values[i][2] = obj.getAccount();
				values[i][3] = obj.getName();
				if(obj.getStatus()==0){
					values[i][4] = "禁用";
				}else if(obj.getStatus()==1){
					values[i][4] = "正常";
				}else if(obj.getStatus()==4){
					values[i][4] = "锁定";
				}else if(obj.getStatus()==5){
					values[i][4] = "冻结";
				}
				values[i][6] = obj.getSubject();
				values[i][7] = obj.getDept();
				values[i][8] = obj.getCostDept();
				values[i][9] = obj.getRankGrade();
				if(obj.getType().equals("0")){
					values[i][10] = "总裁";
				}else if(obj.getType().equals("1")){
					values[i][10] = "体系";
				}else if(obj.getType().equals("2")){
					values[i][10] = "分公司/频道";
				}else if(obj.getType().equals("3")){
					values[i][10] = "部门";
				}else if(obj.getType().equals("4")){
					values[i][10] = "事业厅";
				}else if(obj.getType().equals("5")){
					values[i][10] = "小组";
				}else if(obj.getType().equals("6")){
					values[i][10] = "业务员";
				}else if(obj.getType().equals("7")){
					values[i][10] = "内容总裁";
				}else if(obj.getType().equals("8")){
					values[i][10] = "内容体系";
				}else if(obj.getType().equals("9")){
					values[i][10] = "内容频道";
				}else if(obj.getType().equals("10")){
					values[i][10] = "内容运营小组";
				}else if(obj.getType().equals("11")){
					values[i][10] = "内容主播";
				}
				values[i][11] = obj.getEntryDate()==null?"":DateFormatUtils.format(obj.getEntryDate(), "yyyy-MM-dd HH:mm:ss");
				values[i][12] = obj.getLeaveDate()==null?"":DateFormatUtils.format(obj.getLeaveDate(), "yyyy-MM-dd HH:mm:ss");
				values[i][13] = obj.getPhone();
				/*if(obj.getSex()==0){
					values[i][14] = "男";
				}else {
					values[i][14] = "女";
				}*/
				values[i][14] = obj.getIdCardNum();
				values[i][15] = obj.getBankAccount();
				values[i][16] = obj.getBank();
				values[i][17] = obj.getSalaryTotal().toEngineeringString();
				values[i][18] = obj.getBasePay().toEngineeringString();
				values[i][21] = obj.getBasePayTotal().toEngineeringString();
				values[i][24] = obj.getBonus().toEngineeringString();
				values[i][26] = obj.getBonusTotal().toEngineeringString();
				values[i][29] = obj.getRecommendFee().toEngineeringString();
			}
			outPutExcel(response, title, fileName, sheetName, values);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ERROR.getMsg()), e.getMessage(), null);
		}
		return result;

	}

	/**
	 * 获取主体部门
	 * @param code
	 * @return
	 * @throws Exception
	 */
	private String getSubjectDept(String code) throws Exception{
		Dept dept = this.deptService.selectByCode(code);
		if(dept!=null && StringUtils.isNotBlank(dept.getParentCode())){
			if(dept.getType()==0){
				return dept.getName();
			}else {
				return getSubjectDept(dept.getParentCode());
			}
		}else {
			return null;
		}
	}


	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		OutputStream os = null;
		try {
			HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
			// 将文件存到指定位置
			this.setResponseHeader(response, fileName);
			os = response.getOutputStream();
			wb.write(os);
			os.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}


	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}
}